package com.example.musicserver.controller;

import com.example.musicserver.constant.Constant;
import com.example.musicserver.model.MusicInfo;
import com.example.musicserver.model.Result;
import com.example.musicserver.model.UserInfo;
import com.example.musicserver.service.LoveMusicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/lovemusic")
public class LoveMusicController {
    @Autowired
    private LoveMusicService loveMusicService;
    @RequestMapping("/findlovemusic")
    public Result<Object[]> getList(String musicName, HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        UserInfo userInfo = (UserInfo) session.getAttribute(Constant.USERINFO_SESSION_KEY);
        Integer userId = userInfo.getId();
        List<MusicInfo> list;
        Object[] arr;
        if (musicName == null || musicName.isEmpty()) {
            list = loveMusicService.getList(userId);
        }else {
            list = loveMusicService.getList(userId,musicName);
        }
        arr = list.toArray();
        return Result.success(arr);
    }

    @RequestMapping("/likemusic")
    public Result<Boolean> addLoveMusic(Integer id,HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        UserInfo userInfo = (UserInfo) session.getAttribute(Constant.USERINFO_SESSION_KEY);
        Integer userId = userInfo.getId();
        Integer uid = loveMusicService.getByUidAndMid(userId,id);
        Integer ret;
        if (uid == null || uid < 0) {
            ret = loveMusicService.addLoveMusic(userId,id);
            if (ret > 0) return Result.success("添加喜欢音乐成功",true);
            else return Result.fail(500,"添加喜欢音乐失败，请联系管理员",false);
        }else {
            ret = loveMusicService.deleteLoveMusic(userId,id);
            if (ret == 1) return Result.success("该音乐已从喜欢列表中删除",true);
            else return Result.fail(500,"从列表中删除喜欢音乐失败，请联系管理员",false);
        }
    }

    @RequestMapping("/deletelovemusic")
    public Result<Boolean> delete(Integer id, HttpServletRequest request) {
        if (id == null || id < 0) {
            return Result.fail(500,"前端传输数据错误，或者网络传输过程中出现错误，请联系管理员"
                    ,false);
        }
        UserInfo userInfo = (UserInfo) request.getSession(false).getAttribute(Constant.USERINFO_SESSION_KEY);
        Integer userId = userInfo.getId();
        Integer ret = loveMusicService.deleteLoveMusic(userId,id);
        if (ret == 1) {
            return Result.success(true);
        }else {
            return Result.fail(500,"删除音乐失败，请联系管理员",false);
        }
    }
}
